//
//  CodeFormatUtils.swift
//  MyColorPicker
//
//  Created by 火星人 on 2018/9/22.
//  Copyright © 2018年 火星人. All rights reserved.
//

import Cocoa

class CodeFormatUtils {
    public static func genCodeWithFormat(format array: [String]?, colorComponents: [CGFloat]?) -> String {
        if let array = array {
            let ta = array[0].split(separator: "s")
            for i in ta {
                if i.contains("%") {
                    var ii = i as NSString
                    let pos = ii.range(of: "%", options: .backwards).location
                    let len = ii.length - pos
                    ii = ii.substring(with: NSRange(location: pos, length: len)) as NSString
                    if ii.contains("f") || ii.contains("X") || ii.contains("x") || ii.contains("d") {
                        continue
                    }
                    else{
                        return ""
                    }
                }
            }
            if let comp = colorComponents, array.count > 1 {
                var para = [CVarArg]()
                for i in 1 ... array.count - 1 {
                    let s = array[i]
                    if s == "r" {
                        para.append(comp[0])
                    }
                    else if s == "g" {
                        para.append(comp[1])
                    }
                    else if s == "b" {
                        para.append(comp[2])
                    }
                    else if s == "R" {
                        para.append(Int(comp[0] * 255))
                    }
                    else if s == "G" {
                        para.append(Int(comp[1] * 255))
                    }
                    else if s == "B" {
                        para.append(Int(comp[2] * 255))
                    }
                }
                return String(format: array[0], arguments: para)
            }
        }
        return ""
    }
}
